#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include "db/db_impl.h"
#include "leveldb/db.h"
#include "leveldb/options.h"

namespace leveldb {
const int num = 1000000;
#define value_size 1024

int run() {
    Options options;
    DB *db;
    
    options.create_if_missing = true;
    Status s = DB::Open(options, "/home/zzg/data", &db);
    if (!s.ok()) {
      fprintf(stderr, "open error: %s\n", s.ToString().c_str());
      exit(1);
    }

    int *array = (int *)malloc(num * sizeof(int));
    int i; 
    for(i = 0; i < num; i ++) {
	array[ i ] = i;
    }

    for(i = 0; i < num; i ++) {
	int rand = (random() % num);
	int tmp = array[i];
	array[i] = array[rand];
	array[rand] = tmp;
    }

    char value_data[value_size];
    char key_data[10];

    WriteOptions woptions;
    for(i = 0; i < num; i ++) {
	snprintf(key_data, 10, "%08d", array[i]);
	Status s = db->Put(woptions, Slice(key_data, 8), Slice(value_data, value_size));
//	printf("key: %s.\n", key_data);
	if(!s.ok()) {
	    fprintf(stdout, "put error: %s\n", s.ToString().c_str());
	    exit(1);
	}
    }
    printf("finishing put\n\n");
    
    ReadOptions roptions;
    std::string value;
    int missing = 0;
    for(i = 0; i < num; i ++) {
	snprintf(key_data, 10, "%08d", array[i]);
	Status s = db->Get(roptions, Slice(key_data, 8), &value);
	if(!s.ok()) {
	    missing ++;
	    fprintf(stdout, "get error: %s, key: %s.\n", s.ToString().c_str(), key_data);
//	    exit(1);
	}
    }    
    printf("finishing get\n");
    printf("missing %d\n", missing);
    
    return 0;
}
}

int main() {
    leveldb::run();
    return 0;
}
